'use strict';

const {
	ESPIPE
} = require('constants');
const crypto = require('crypto');
const https = require('https');


module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/kh/yhsj/czjl/xnzf/refund前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {

		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			pid,
			openid,
			order_id,
			user_id,
			order_fee,
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		
		console.log("data",data);
	

		// 具体用户
		let res1 = await vk.baseDao.selects({
			dbName: "uni-id-users",
			// 主表where条件
			whereJson: {
				_id: user_id
			},
		})
		console.log("res1",res1);
		
		// 具体小程序名称	
		let res2 = await vk.baseDao.selects({
			dbName: "a_appid",
			// 主表where条件
			whereJson: {
				appname: res1.rows[0].register_env.app_name
			},
		})
		
		console.log("res2",res2);
		
		let res3 = await vk.baseDao.selects({
			dbName: "vk-pay-config",
			// 主表where条件
			whereJson: {
				"wxpay.mp-weixin.appId": res2.rows[0].appid
			},
		})
		
		console.log("res3",res3);


		let AppKey = res3.rows[0].wxpay["mp-weixin"].AppKey
		let OfferID = res3.rows[0].wxpay["mp-weixin"].OfferID
		let secret = res3.rows[0].wxpay["mp-weixin"].secret
		let appId = res3.rows[0].wxpay["mp-weixin"].appId

		let uri = "/xpay/refund_order" // 退款

		let appkey = AppKey

		// 退款
		let post_body = JSON.stringify({
			openid: openid,
			order_id: order_id, //支付单号
			refund_order_id: order_id + '7', // 退款单号
			left_fee: order_fee, // 当前单剩余可退余额
			refund_fee: order_fee , // 退款金额  单位 分
			biz_meta: "自定义", // 自定义数据
			refund_reason: "5", // 退款原因
			req_from: "3", // 退款来源
			env: 0, // 环境
		});
	
		
		let access_token = await getAccessToken();
		
		let paySig = calc_pay_sig(uri, post_body, appkey);
		
		let refundOrder = await refund_order(access_token, paySig);
		res.refundOrder = JSON.parse(refundOrder)
		
		res.order_fee = order_fee


		// 业务逻辑结束-----------------------------------------------------------
		return res;

		// 支付签名
		function calc_pay_sig(uri, post_body, appkey) {
			const need_sign_msg = uri + '&' + post_body;
			const pay_sig = crypto.createHmac('sha256', appkey).update(need_sign_msg).digest('hex');
			return pay_sig;
		}


		// 获取 access_token
		async function getAccessToken() {
			const data = JSON.stringify({
				grant_type: 'client_credential',
				appid: appId,
				secret: secret,
			});
			const formUrl = 'https://api.weixin.qq.com/cgi-bin/stable_token';

			try {
				const response = await uniCloud.httpclient.request(formUrl, {
					method: 'POST',
					data: data,
				});
				const results = (response.data).toString('utf-8');
				// 字符串转换为对象
				const resultsStr = JSON.parse(results).access_token
				return resultsStr;
			} catch (error) {
				console.log('请求错误', error);
				throw error;
			}

		}


		// 退款
		async function refund_order(access_token, paySig) {

			const data = post_body
			const formUrl =
				`https://api.weixin.qq.com/xpay/refund_order?access_token=${access_token}&pay_sig=${paySig}`;

			try {
				const response = await uniCloud.httpclient.request(formUrl, {
					method: 'POST',
					data: data,
				});
				const results = response.data.toString('utf-8');
				console.log("退款信息", results);

				return results;
			} catch (error) {
				console.log('请求错误', error);
				throw error;
			}

		}
	}
}